﻿using Newtonsoft.Json;
using System.Net;
using Scheduler.Model;
using Scheduler.Common.Helper;

namespace Scheduler.WebAPI
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IHostEnvironment _environment;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, IHostEnvironment environment, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _environment = environment;
            _logger = logger;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";
            string errorMsg = $"错误消息:{exception.Message}{Environment.NewLine}错误追踪:{exception.StackTrace}";
            _logger.LogError(errorMsg);
            string message = _environment.IsDevelopment() ? exception.Message : "抱歉，服务端出错了！";
            var errorResult = MessageModel<object>.ErrorResult(message);
            return context.Response.WriteAsync(JsonConvert.SerializeObject(errorResult));
        }
    }
}
